package com.doctor.windflower_doctor.adapter;

import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.doctor.windflower_doctor.R;
import com.doctor.windflower_doctor.SystemApplication;
import com.doctor.windflower_doctor.activity.BaseActivity;
import com.doctor.windflower_doctor.activity.QuestionOnLineActivity;
import com.doctor.windflower_doctor.activity.SickDetailActivity;
import com.doctor.windflower_doctor.db.SharedPreferencesDB;
import com.doctor.windflower_doctor.delegate.PlayAudio;
import com.doctor.windflower_doctor.download.DownloadManager;
import com.doctor.windflower_doctor.download.DownloadService;
import com.doctor.windflower_doctor.entity.DialogueBeen;
import com.doctor.windflower_doctor.entity.DownloadInfo;
import com.doctor.windflower_doctor.fragment.MenuFragment;
import com.doctor.windflower_doctor.pop.BigImagePopWindow;
import com.doctor.windflower_doctor.util.Constent;
import com.doctor.windflower_doctor.util.LogUtils;
import com.doctor.windflower_doctor.util.PlayManager;
import com.doctor.windflower_doctor.util.StringUtil;
import com.doctor.windflower_doctor.view.ImagePopUtil;
import com.doctor.windflower_doctor.view.RoundedImageView;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

public class OnLineTalkWithAdapter extends BaseAdapter {
	private Context context;
	private LayoutInflater inflater;
	private List<DialogueBeen> dialogueBeens;
	private DisplayImageOptions options;
	private DownloadManager downloadManager;
	private PlayManager playManager;
	private String userId;
	private ImagePopUtil imagePopUtil;
	private boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

	public OnLineTalkWithAdapter(Context context, String userId) {
		this.context = context;
		this.inflater = LayoutInflater.from(context);
		this.userId = userId;
		dialogueBeens = new ArrayList<DialogueBeen>();
		downloadManager = DownloadService.getDownloadManager(context);
		playManager = new PlayManager();
		WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		int window_width = manager.getDefaultDisplay().getWidth();
		int window_height = manager.getDefaultDisplay().getHeight();
		imagePopUtil = new ImagePopUtil((BaseActivity) context, window_width, window_height);
		options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.loading_img).showImageOnFail(R.drawable.loading_img)
				.showImageForEmptyUri(R.drawable.loading_img).cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.ARGB_8888).build();
	}

	@Override
	public int getCount() {
		return dialogueBeens.size();
	}

	@Override
	public Object getItem(int position) {
		return dialogueBeens.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public int getViewTypeCount() {
		return 2;
	}

	@Override
	public int getItemViewType(int position) {
		if (!dialogueBeens.isEmpty() && dialogueBeens.size() > 0)
			return dialogueBeens.get(position).isDoctor ? 0 : 1;
		return -1;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final DialogueBeen dialogueBeen = dialogueBeens.get(position);
		ViewHolder holder = null;
		if (convertView == null) {
			holder = new ViewHolder();
			if (dialogueBeen.isDoctor) {
				convertView = inflater.inflate(R.layout.chat_to_item, null);
			} else {
				convertView = inflater.inflate(R.layout.chat_from_item, null);
			}
			holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
			holder.voice_time = (TextView) convertView.findViewById(R.id.voice_time);
			holder.iv_user_image = (RoundedImageView) convertView.findViewById(R.id.iv_user_image);
			holder.image1 = (ImageView) convertView.findViewById(R.id.image1);
			holder.image2 = (ImageView) convertView.findViewById(R.id.image2);
			holder.image3 = (ImageView) convertView.findViewById(R.id.image3);
			holder.voice_img = (ImageView) convertView.findViewById(R.id.voice_img);
			holder.name_text = (TextView) convertView.findViewById(R.id.name_text);
			holder.position_text = (TextView) convertView.findViewById(R.id.position_text);
			holder.tv_content = (TextView) convertView.findViewById(R.id.tv_content);
			holder.content_box = (LinearLayout) convertView.findViewById(R.id.content_box);
			holder.img_layout = (LinearLayout) convertView.findViewById(R.id.img_layout);
			holder.user_infermation_layout = (LinearLayout) convertView.findViewById(R.id.user_infermation_layout);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.image1.destroyDrawingCache();
		holder.image1.setVisibility(View.GONE);
		holder.image2.destroyDrawingCache();
		holder.image2.setVisibility(View.GONE);
		holder.image3.destroyDrawingCache();
		holder.image3.setVisibility(View.GONE);
		holder.tv_content.setVisibility(View.GONE);
		holder.voice_img.setVisibility(View.GONE);
		holder.voice_time.setVisibility(View.GONE);
		holder.img_layout.setVisibility(View.GONE);

		holder.tv_time.setText(dialogueBeen.createTime);
		holder.name_text.setText(dialogueBeen.nick);
		SystemApplication.getInstance().mImageLoad1.displayImage(dialogueBeen.imgUrl, holder.iv_user_image, options);
		holder.iv_user_image.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				LogUtils.e("=====id====" + userId + "=====SharedPreferencesDB.getInstance(context).getDocotorId()==="
						+ SharedPreferencesDB.getInstance(context).getDocotorId());
				if (!dialogueBeen.isDoctor) {
					Intent intent = new Intent(context, SickDetailActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString(Constent.USERID, userId);
					intent.putExtras(bundle);
					context.startActivity(intent);
				}
			}
		});

		if (!StringUtil.isEmpty(dialogueBeen.audio)) {
			LogUtils.e("===========dialogueBeen.audio============" + dialogueBeen.audio);
			WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
			int width = wm.getDefaultDisplay().getWidth();
			LogUtils.e("=========widthConvertView============" + width);
			int widthContent_box = getWidth(holder.content_box);
			LogUtils.e("=========widthContent_box============" + widthContent_box);
			int widthUser_infermation_layout = getWidth(holder.user_infermation_layout);
			LogUtils.e("=========widthUser_infermation_layout============" + widthUser_infermation_layout);
			int currentWidth = (width - widthUser_infermation_layout - 100 - widthContent_box) / 60;
			String target = null;
			if (sdCardExist) {
				target = Environment.getExternalStorageDirectory().getAbsolutePath() + "/." + context.getPackageName() + "/.audio/"
						+ System.currentTimeMillis() + ".amr";
			} else {
				target = context.getFilesDir().getAbsolutePath() + "/.audio/" + System.currentTimeMillis() + ".amr";
			}
			try {
				downloadManager.addNewDownload(dialogueBeen.audio.toString().trim() + ".amr", "windflower_doctor", target, true, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
						false, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
						null);
			} catch (DbException e) {
				LogUtils.e(e.toString());
			}
			holder.voice_time.setVisibility(View.VISIBLE);
			holder.voice_time.setText(dialogueBeen.size + "\"");
			holder.voice_img.setVisibility(View.VISIBLE);
			holder.voice_img.setOnClickListener(new PlayClick(holder.voice_img, dialogueBeen.audio));
			holder.content_box.setMinimumWidth(currentWidth * Integer.parseInt(dialogueBeen.size) + widthContent_box);
			holder.content_box.setOnClickListener(new PlayClick(holder.voice_img, dialogueBeen.audio));
		} else {
			if (!StringUtil.isEmpty(dialogueBeen.text)) {
				holder.tv_content.setVisibility(View.VISIBLE);
				holder.tv_content.setText(dialogueBeen.text);
			}
			if (dialogueBeen.images.size() > 0) {
				holder.img_layout.setVisibility(View.VISIBLE);
				switch (dialogueBeen.images.size()) {
				case 3:
					holder.image3.setVisibility(View.VISIBLE);
					SystemApplication.getInstance().mImageLoad1.displayImage(dialogueBeen.images.get(2).image, holder.image3, options);
					holder.image3.setOnClickListener(new BigImageClick(dialogueBeen.images.get(2).image));
				case 2:
					holder.image2.setVisibility(View.VISIBLE);
					SystemApplication.getInstance().mImageLoad1.displayImage(dialogueBeen.images.get(1).image, holder.image2, options);
					holder.image2.setOnClickListener(new BigImageClick(dialogueBeen.images.get(1).image));
				case 1:
					holder.image1.setVisibility(View.VISIBLE);
					SystemApplication.getInstance().mImageLoad1.displayImage(dialogueBeen.images.get(0).image, holder.image1, options);
					holder.image1.setOnClickListener(new BigImageClick(dialogueBeen.images.get(0).image));
					break;
				}
			}
		}
		return convertView;
	}

	class BigImageClick implements OnClickListener {
		String url;

		BigImageClick(String url) {
			this.url = url;
		}

		@Override
		public void onClick(View V) {
			BigImagePopWindow bigImagePopWindow = new BigImagePopWindow((BaseActivity) context, url);
			bigImagePopWindow.show();
			// imagePopUtil.showImagePopupWindow(url);
		}

	}

	public void addListData(List<DialogueBeen> dialogueBeens) {
		if (dialogueBeens != null && dialogueBeens.isEmpty()) {
			return;
		}
		this.dialogueBeens.addAll(dialogueBeens);
		notifyDataSetChanged();
	}

	public void clearData() {
		this.dialogueBeens.clear();
		notifyDataSetChanged();
	}

	class ViewHolder {
		TextView tv_time;
		TextView voice_time;
		RoundedImageView iv_user_image;
		TextView name_text;
		TextView position_text;
		TextView tv_content;
		ImageView image1;
		ImageView image2;
		ImageView image3;
		ImageView voice_img;
		LinearLayout content_box;
		LinearLayout img_layout;
		LinearLayout user_infermation_layout;
	}

	class PlayClick implements OnClickListener {
		ImageView imageView;
		String url;

		PlayClick(ImageView imageView, String url) {
			this.imageView = imageView;
			this.url = url;
		}

		@Override
		public void onClick(View v) {
			imageView.setBackgroundResource(R.drawable.paly_anim);
			final AnimationDrawable anim = (AnimationDrawable) imageView.getBackground();
			DbUtils dbUtils = DbUtils.create(context);

			List<DownloadInfo> downloadInfos = null;
			try {
				downloadInfos = dbUtils.findAll(Selector.from(DownloadInfo.class).where("downloadUrl", "=", url.toString().trim() + ".amr"));
			} catch (DbException e) {
				e.printStackTrace();
			}

			if (downloadInfos != null && downloadInfos.size() > 0) {
				LogUtils.e("===============OnLineTalkWithAdapter==================" + downloadInfos.size());
				playManager.playUrl(downloadInfos.get(0).getFileSavePath());
				playManager.setPlayAudio(new PlayAudio() {

					@Override
					public void audioStop(boolean isStop) {
						LogUtils.e("===============audioStop==================");
						imageView.setBackgroundResource(R.drawable.play);
						anim.stop();
					}

					@Override
					public void audioPlay(boolean isPlay) {
						anim.start();
					}
				});
				anim.start();
			}

		}
	}

	public void stopAudio() {
		playManager.stopManager();
	}

	public static int getWidth(View view) {
		int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
		int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
		view.measure(w, h);
		return (view.getMeasuredWidth());
	}
}
